package com.yz.kronos.executor;

import com.yz.kronos.common.Model;
import com.yz.kronos.executor.exception.StartupException;
import com.yz.kronos.executor.trigger.DistributedTrigger;
import com.yz.kronos.executor.trigger.StandAloneTrigger;
import com.yz.kronos.executor.trigger.Trigger;
import org.springframework.boot.ApplicationArguments;
import org.springframework.context.annotation.Bean;

import java.util.List;

import static com.yz.kronos.common.Constant.MODEL;
import static com.yz.kronos.common.Constant.SCHEDULER_URL;
import static com.yz.kronos.common.Constant.TRIGGER_PARAMS;

/**
 * 自动配置
 * @author shanchong
 * @date 2021/11/23
 **/
public class AutoConfiguration {

    @Bean
    public Trigger trigger(ApplicationArguments applicationArguments) {
        List<String> modelList = applicationArguments.getOptionValues(MODEL);
        List<String> schedulerUrls = applicationArguments.getOptionValues(SCHEDULER_URL);
        List<String> triggerParams = applicationArguments.getOptionValues(TRIGGER_PARAMS);
        if (modelList==null || modelList.isEmpty()) {
            throw new StartupException("Not found command args model.");
        }
        String model = modelList.get(0);
        if (Model.DISTRIBUTED.name().equals(model)) {
            if (schedulerUrls.isEmpty() || "".equals(schedulerUrls.get(0))) {
                throw new StartupException("Distributed model but not found " + SCHEDULER_URL);
            }
            return new DistributedTrigger();
        }
        if (Model.STAND_ALONE.name().equals(model)) {
            if (triggerParams.isEmpty() || "".equals(triggerParams.get(0))) {
                throw new StartupException("StandAlone model but not found " + TRIGGER_PARAMS);
            }
            return new StandAloneTrigger();
        }
        throw new StartupException("Unable to identify model.");
    }
}
